package com.atguigu.edu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.KafkaUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author Lec
 * @date 2022/9/3 16:12
 */

public class BaseLogApp {
    public static void main(String[] args) throws Exception {
        //TODO 1. 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);
        //TODO 2. 设置状态后端
        /*
        env.enableCheckpointing(5 * 60 * 1000L, CheckpointingMode.EXACTLY_ONCE );
        env.getCheckpointConfig().setCheckpointTimeout( 3 * 60 * 1000L );
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
        System.setProperty("HADOOP_USER_NAME", "atguigu");
        */


// TODO 3 读取kafka主题topic_log中的数据
        String topic = "topic_log";
        String groupID = "base_log_app";
        DataStreamSource<String> streamSource = env.addSource(KafkaUtil.getKafkaConsumer(topic, groupID+"_pl"));
        // TODO 4 清洗转换数据   将脏数据输出到侧输出流 加上这个要求以后就只能用process算子了
//        处理来自kafka的不是json格式的数据（其实这里在flume的拦截器中已经处理过了，我们写上 更完整一些）
//        streamSource.map(new MapFunction<String, JSONObject>() {
//            @Override
//            public JSONObject map(String value) throws Exception {
//
//                try {
//                    JSONObject jsonObject = JSON.parseObject(value);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                return null;
//            }
//        })

        OutputTag<String> outputTag = new OutputTag<String>("Dirty") {
        };

        SingleOutputStreamOperator<JSONObject> logStream = streamSource.process(new ProcessFunction<String, JSONObject>() {
            @Override
            public void processElement(String value, Context ctx, Collector<JSONObject> out) throws Exception {
                try {
                    JSONObject jsonObject = JSON.parseObject(value);
                    out.collect(jsonObject);
                } catch (Exception e) {
                    ctx.output(outputTag, value);
                    e.printStackTrace();
                }
            }
        });

        // TODO 5 根据mid分组数据
        KeyedStream<JSONObject, String> keyedStream = logStream.keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject value) throws Exception {
                return value.getJSONObject("common").getString("mid");
            }
        });
        // TODO 6 根据键控状态完成新旧访客的标记修复
//        修改新访客标记的逻辑是什么？
//        日志中的标记为1  -> mid做为key  value为首次登录日期
//        真的新访客  value为空或者value和当前登录的日期是同一天  今日时间写入状态
//        重新安装的APP  value不为空并且和当前登录的日期不是同一天 将标记改为0
//        日志中的标记为0  -> mid做为key  value为首次登录日期
//        真的旧访客  value有值并且日期不是同一天
//        真的旧访客  value为null  补充一个状态 添加一个value值
//        (只要是以前的时间不是今天和以后就行)
        SingleOutputStreamOperator<JSONObject> repairStream = keyedStream.map(new RichMapFunction<JSONObject, JSONObject>() {
            private ValueState<String> firstValueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                firstValueState = getRuntimeContext().getState(new ValueStateDescriptor<String>("first_login_date", String.class));
            }

            @Override
            public JSONObject map(JSONObject value) throws Exception {
                String is_new = value.getJSONObject("common").getString("is_new");
                String firstDate = firstValueState.value();
                String loginDate = DateFormatUtil.toDate(value.getLong("ts"));

                if ("1".equals(is_new)) {
                    //        真的新访客  value为空或者value和当前登录的日期是同一天
                    if (firstDate == null) {
                        firstValueState.update(loginDate);
                    } else if (!loginDate.equals(firstDate)) {
                        //        重新安装的APP  value不为空并且和当前登录的日期不是同一天 将标记改为0
                        value.getJSONObject("common").put("is_new", 0);
                    }

                } else {
                    //        真的旧访客  value有值并且日期不是同一天 不操作
                    //        真的旧访客  value为null  补充一个状态 添加一个value值
                    if (firstDate == null) {
                        String yesterday = DateFormatUtil.toDate(value.getLong("ts") - 24 * 60 * 60 * 1000L);
                        firstValueState.update(yesterday);
//                        System.out.println(yesterday);
                    }
                }
                return value;
            }
        });
//        repairStream.print("isNew>>>>>>>>");

        // TODO 7 将数据拆分为5种数据流
        OutputTag<String> errTag = new OutputTag<String>("err") {
        };
        OutputTag<String> startTag = new OutputTag<String>("start") {
        };
        OutputTag<String> actionTag = new OutputTag<String>("action") {
        };
        OutputTag<String> displayTag = new OutputTag<String>("display") {
        };
        OutputTag<String> appVideoTag = new OutputTag<String>("appVideo") {
        };
        SingleOutputStreamOperator<String> pageStream = repairStream.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject value, Context ctx, Collector<String> out) throws Exception {
                //输出错误信息
                String err = value.getString("err");
                if (err != null) {
                    ctx.output(errTag, err);
                    value.remove("err");
                }

                //输出启动日志
                JSONObject start = value.getJSONObject("start");
                String appVideo = value.getString("appVideo");
                if (start != null) {
                    ctx.output(startTag, value.toJSONString());
                } else if (appVideo != null) {
                    //输出播放日志
                    ctx.output(appVideoTag,value.toJSONString() );
                } else  {
                    //页面日志

                    JSONObject common = value.getJSONObject("common");
                    Long ts = value.getLong("ts");/*这里是getLong*/
                    JSONObject page = value.getJSONObject("page");

                    //输出行为日志
                    JSONArray actions = value.getJSONArray("actions");
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.put("common", common);
                            action.put("ts", ts);
                            action.put("page", page);

                            ctx.output(actionTag, action.toJSONString());
                        }
                    }
                    value.remove("actions");

                    //输出曝光日志
                    JSONArray displays = value.getJSONArray("displays");
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.put("common", common);
                            display.put("ts", ts);
                            display.put("page", page);

                            ctx.output(displayTag, display.toJSONString());
                        }
                    }
                    value.remove("displays");

                    //输出页面日志
                    out.collect(value.toJSONString());

                }


            }
        });

        DataStream<String> startStream = pageStream.getSideOutput(startTag);
        DataStream<String> appVideoStream = pageStream.getSideOutput(appVideoTag);
        DataStream<String> errStream = pageStream.getSideOutput(errTag);
        DataStream<String> actionStream = pageStream.getSideOutput(actionTag);
        DataStream<String> displayStream = pageStream.getSideOutput(displayTag);

        pageStream.print("page>>>>>>>>");
        startStream.print("start>>>>>>>>>");
        appVideoStream.print("appVideoTag>>>>>>>>>>");
        errStream.print("err>>>>>>>>>");
        actionStream.print("action>>>>>>>>>");
        displayStream.print("display>>>>>>>>>");

        // TODO 8 将5种数据流写回到对应的kafka主题
        String error_topic = "dwd_traffic_error_log";
        String start_topic = "dwd_traffic_start_log";
        String video_topic = "dwd_traffic_video_log";
        String action_topic = "dwd_traffic_action_log";
        String display_topic = "dwd_traffic_display_log";
        String page_topic = "dwd_traffic_page_log";


        errStream.addSink(KafkaUtil.getKafkaProducer(error_topic));
        startStream.addSink(KafkaUtil.getKafkaProducer(start_topic));
        appVideoStream.addSink(KafkaUtil.getKafkaProducer(video_topic));
        actionStream.addSink(KafkaUtil.getKafkaProducer(action_topic));
        displayStream.addSink(KafkaUtil.getKafkaProducer(display_topic));
        pageStream.addSink(KafkaUtil.getKafkaProducer(page_topic));


        // TODO 执行任务
        env.execute();
    }
}
